package com.htthorizon.util;


import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.google.common.base.Charsets;
import com.htthorizon.common.core.utils.StringUtils;
import com.htthorizon.common.security.utils.SecurityUtils;
import com.htthorizon.model.service.IModelCrossAuditService;
import com.htthorizon.system.api.domain.SysDept;
import com.htthorizon.system.api.domain.SysUser;
import com.htthorizon.system.api.model.LoginUser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author Brilliant
 */
@Component
@Data
@Slf4j
@Deprecated
public class ServiceMarketHTTPUtil {

    @Value("${serviceMarket.host}")
    private  String host;

    @Autowired
    private IModelCrossAuditService modelCrossAuditService;


    public String getMethod(String host,String appKey,String appSecurty,String path,String params) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        String pathAndParams=path;
        if (StringUtils.isNotEmpty(params)){
            pathAndParams =path+ "?"+params;
        }
        String url=new String((host+pathAndParams).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);

        log.info("apiURL:{}",url);

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");
        Matcher m = p.matcher(url);

        StringBuffer url2 = new StringBuffer();

        while (m.find()) {
            m.appendReplacement(url2, URLEncoder.encode(m.group(0), "utf-8"));
        }

        m.appendTail(url2);
        log.info("编码后的url: {}",url2);


        String method = "GET";
        String accept = "*/*";
        String contentMD5 = "";
        String contentType = "";
        String date = "";

        String sign = this.getSign(method, accept, contentMD5, contentType, date, pathAndParams);

        log.info("sign : {}" ,sign);

//        String strBase64 = Base64.decodeStr(sign, "UTF-8");
//        String strBase64 = encodeBase64(sign);
        String strBase64 = this.calculateHmacSha256(sign, appSecurty);
        log.info("strBase64 : {}" , strBase64);

        HttpResponse execute = HttpRequest.get(url2.toString())
                .header("Host", "<calculated when request is sent>")
                .header("x-ca-key", appKey)
                .header("x-ca-signature", strBase64)
                .header("x-ca-signature-method", "HmacSHA256")
                .header("Accept", "*/*")
                .header("Content-MD5", "")
                .header("Content-Type", "")
                .header("Data", "")
                .execute();

        String responseBody = execute.body();
//        log.info("responseBody : {}" , responseBody);
        return responseBody;
    }

    public String getMethod1(String appKey,String appSecurty,String path,String params) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        String pathAndParams =path+ "?"+"pageNum=1&pageSize=10";
        String url=host+pathAndParams;

        log.info("apiURL:{}",url);

        String method = "GET";
        String accept = "*/*";
        String contentMD5 = "";
        String contentType = "";
        String date = "";

        String sign = this.getSign(method, accept, contentMD5, contentType, date, pathAndParams);

        log.info("sign : {}" ,sign);

//        String strBase64 = Base64.decodeStr(sign, "UTF-8");
//        String strBase64 = encodeBase64(sign);
        String strBase64 = this.calculateHmacSha256(sign, appSecurty);
        log.info("strBase64 : {}" , strBase64);

        HttpResponse execute = HttpRequest.get(url)
                .header("Host", "<calculated when request is sent>")
                .header("x-ca-key", appKey)
                .header("x-ca-signature", strBase64)
                .header("x-ca-signature-method", "HmacSHA256")
                .header("Accept", "*/*")
                .header("Content-MD5", "")
                .header("Content-Type", "")
                .header("Data", "")
                .execute();

        String responseBody = execute.body();
//        log.info("responseBody : {}" , responseBody);
        return responseBody;
    }


    public String getMethod2(String appKey,String appSecurty,String path,String params) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        String pathAndParams =path+ "?"+"pageNum=1&pageSize=1000";
        String url=host+pathAndParams;

        log.info("apiURL:{}",url);

        String method = "GET";
        String accept = "*/*";
        String contentMD5 = "";
        String contentType = "";
        String date = "";

        String sign = this.getSign(method, accept, contentMD5, contentType, date, pathAndParams);

        log.info("sign : {}" ,sign);

//        String strBase64 = Base64.decodeStr(sign, "UTF-8");
//        String strBase64 = encodeBase64(sign);
        String strBase64 = this.calculateHmacSha256(sign, appSecurty);
        log.info("strBase64 : {}" , strBase64);

        HttpResponse execute = HttpRequest.get(url)
                .header("Host", "<calculated when request is sent>")
                .header("x-ca-key", appKey)
                .header("x-ca-signature", strBase64)
                .header("x-ca-signature-method", "HmacSHA256")
                .header("Accept", "*/*")
                .header("Content-MD5", "")
                .header("Content-Type", "")
                .header("Data", "")
                .execute();

        String responseBody = execute.body();
        log.info("responseBody : {}" , responseBody);
        return responseBody;
    }


    public String get1(String appKey, String path,String base64) {
        String url=host+path+"?pageNum=1&pageSize=10";
        String method = "GET";
        String accept = "*/*";
        String contentMD5 = "";
        String contentType = "";
        String date = "";
        System.err.println("url = " + url);
        String pathAndParam =path+ "?"+"pageNum=1&pageSize=10";
        System.err.println("pathAndParam = " + pathAndParam);
        String sign = getSign(method, accept, contentMD5, contentType, date, pathAndParam);
        System.err.println("sign = " + sign);
//        String strBase64 = Base64.decodeStr(sign, "UTF-8");
        String strBase64 = encodeBase64(sign);
        System.err.println("appKey = " + appKey);
        System.err.println("strBase64 = " + strBase64);
        System.err.println("base"+base64);
        HttpResponse execute = HttpRequest.get(url)
                .header("Host","<calculated when request is sent>")
                .header("x-ca-key", appKey)
                .header("x-ca-signature", base64)
                .header("x-ca-signature-method", "HmacSHA256")
                .header("Accept", "*/*")
                .header("Content-MD5", "")
                .header("Content-Type", "")
                .header("Data", "")
                .execute();
        String body = execute.body();
        System.err.println(execute);
        System.err.println(body);
        return body;
    }

    public  String getParamString(Map<String,Object> params){

//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        SysUser sysUser = loginUser.getSysUser();
//        SysDept dept = Optional.ofNullable(sysUser.getDept())
//                .orElse(new SysDept());
//
//        if (!sysUser.isAdmin()){
//            List<String> modelCrossAuditStringList = modelCrossAuditService.getModelCrossAuditStringList();
//            modelCrossAuditStringList.add(dept.getDeptName());
//            if ( modelCrossAuditStringList.size() == 1 ){
//                params.put("std_city_org_nm",modelCrossAuditStringList.get(0));
//            }
//        }


        if(params==null || params.size()==0){
            return "";
        }else{
            StringBuilder sb = new StringBuilder();
            String pageNum = params.get("pageNum").toString();
            String pageSize = params.get("pageSize").toString();
            sb.append("pageNum=").append(pageNum).append("&pageSize=").append(pageSize).append("&");
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (!(entry.getKey().equals("pageNum"))&&!(entry.getKey().equals("pageSize"))){
                    sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }

            }
            return sb.substring(0, sb.length() - 1);
        }
    }

    private String getSign(String ...params){
        StringBuilder temp=new StringBuilder();

        for (String param : params) {
            temp.append(param);
            temp.append("\n");
        }
        String s = new String(temp.toString().getBytes(StandardCharsets.UTF_8));
        String s1 = s.replaceFirst("\\n$", "");
        return s1;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
//        ServiceMarketHTTPUtil serviceMarketHTTPUtil = new ServiceMarketHTTPUtil();
//        String sign = serviceMarketHTTPUtil.getSign();
//        System.out.println(sign);
//        System.out.println("Base64.decodeStr(\"你好\") = " + Base64.decodeStr("GET"));
//        ServiceMarketHTTPUtil serviceMarketHTTPUtil = new ServiceMarketHTTPUtil();
//        String str= "GET\n*/*\n\n\n\n/cst/shuzhsjcyhmxeq/rds/get_inhabitant_large_elecqtmf_sf?pageNum=1&pageSize=10";
//        String str2="GET\n*/*\n\n\n\n/cst/shuzhsjcyhmxeq/rds/get_inhabitant_large_elecqtmf_sf?pageSize=10&pageNum=1&test=长沙";
//        System.out.println(str);
//        String sign = generateSign(str, "f47b149c22034765b6162b79ec67de84");
//
//        String s = serviceMarketHTTPUtil.calculateHmacSha256(str, "f47b149c22034765b6162b79ec67de84");
//        String s2 = serviceMarketHTTPUtil.calculateHmacSha256(str2, "f47b149c22034765b6162b79ec67de84");
//        System.out.println("s = " + s);
//        System.out.println("s2 = " + s2);
//        boolean equals = s.equals("PD8mSgNGTDGVKUvRqsyoO//TBq4iaqYPsrIQTOwohh4=");
//        boolean equals1 = s2.equals("PD8mSgNGTDGVKUvRqsyoO//TBq4iaqYPsrIQTOwohh4=");
//        System.out.println(equals);
//        System.out.println(equals1);
//
//        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
//        byte[] appSecretBytes = "f47b149c22034765b6162b79ec67de84".getBytes(StandardCharsets.UTF_8);
//        hmacSha256.init(new SecretKeySpec(appSecretBytes, 0, appSecretBytes.length, "HmacSHA256"));
//        byte[] md5Result = hmacSha256.doFinal(str.getBytes(StandardCharsets.UTF_8));
////        String signature = Base64.encodeBase64String(md5Result);
//        String s1 = encodeBase64(new String(md5Result,StandardCharsets.UTF_8));
//
//        byte[] bytes = str2.getBytes(StandardCharsets.UTF_8);
//        byte[] bytes1 = str2.getBytes(Charsets.ISO_8859_1);
//        for (int i = 0; i < bytes.length; i++) {
//            System.out.print(bytes[i]);
//        }
//        System.out.println();
//        for (int i = 0; i < bytes1.length; i++) {
//            System.out.print(bytes1[i]);
//        }
//        System.out.println();
//
//        System.out.println("new String( bytes, StandardCharsets.UTF_8) = " + new String(bytes, StandardCharsets.UTF_8));
//        String str3="长沙";
//        String s3 = encodeBase64(str3);
//        System.out.println(s3);
//        String s = encodeBase64(str);
//        System.out.println(URLEncoder.encode("/你好"));
//        Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");
//        String a = "https://kos-oss-test.oss-cn-hangzhou.aliyuncs.com/images/企业微信截图_20211229e0a4899a905a4b6d8f0f2d88f8288cd0%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_16407530994802.png";
//        Matcher m = p.matcher(str2);
//        StringBuffer b = new StringBuffer();
//        while (m.find()) {m.appendReplacement(b, URLEncoder.encode(m.group(0), "utf-8"));
//        }
//        m.appendTail(b);
//        System.out.println(b.toString());
//        String s = new String("长沙".getBytes(), StandardCharsets.UTF_8);
//        System.out.println(URLEncoder.encode(s));
//        System.out.println(URLEncoder.encode(new String("长沙".getBytes(), StandardCharsets.ISO_8859_1)));
//        byte[] bytes = "长沙".getBytes(StandardCharsets.UTF_8);
//        for (byte b:bytes){
//
//        }
//        System.out.println(HexUtil.encodeHexStr("长沙", CharsetUtil.CHARSET_UTF_8));

        Map<String, Object> map = new LinkedHashMap<>();


        map.put("pageSize","1000");
        map.put("pageNum","1");
        map.put("std_city_org_nm","长沙");

//        String paramString = getParamString(map);
//        System.out.println(paramString);

    }


    private static   String encodeBase64(String originalString) {
        return Base64.getEncoder().encodeToString(originalString.getBytes(StandardCharsets.UTF_8));
    }







    public static String generateSign(String sign_text, String self_APPSECRET) {
        try {
            byte[] signBytes = sign_text.getBytes(StandardCharsets.UTF_8);
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] digest = md.digest(signBytes);
            byte[] encodedBytes = Base64.getEncoder().encode(digest);
            return new String(encodedBytes, StandardCharsets.UTF_8);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    private  String calculateHmacSha256(String text,String secretKey) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec hmacSHA2561 = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        hmacSHA256.init(hmacSHA2561);
        byte[] src = hmacSHA256.doFinal(text.getBytes(StandardCharsets.UTF_8));
        byte[] encode = Base64.getEncoder().encode(src);
        return new String(encode,StandardCharsets.UTF_8);
    }
}
